package mcts

import (
	"bindolabs/gomoku/modules/gomoku_env"
	"fmt"
	"time"
)

var Root *MCTSNode

func Run() {
	env := gomoku_env.NewGomokuEnv()
	env.Reset()
	Root = NewMCTSNode(env, nil)

	bestNode := &MCTSNode{}
	bestNode = MCTS(Root, 10000000)

	fmt.Println("Best Move:")
	bestNode.Env.ShowBoard()
}

func ShowMCTSNode(env *gomoku_env.GomokuEnv) {
	// time.Sleep(time.Millisecond * 200)
	if 1 == 1 || env.IsTerminal() {
		ShowTree(Root, 0)
		env.ShowBoard()
		c := 'a'
		fmt.Scanf("%c", &c)
		time.Sleep(time.Millisecond * 200)
	}
}

func ShowTree(node *MCTSNode, index int) {
	node.ShowMsg("->")
	for i, n := range node.Children {
		ShowTree(n, i)
	}
}

func (node *MCTSNode) ShowMsg(direction string) {
	startMsg := node.pos
	// fmt.Sprintf("%d,%d", node.depth, index)
	for i := 0; i < node.depth; i++ {
		startMsg += " "
	}
	stateID := fmt.Sprint(int(node.Player))
	for i := 0; i < len(node.State); i++ {
		for j := 0; j < len(node.State); j++ {
			stateID += fmt.Sprintf("%d", node.State[i][j])
		}
	}
	fmt.Printf("%v %v [v:%.2f ucb1:%.2f depth:%d from-action:%v untry-actions:%v visits:%v children:%v state:%v]\n", startMsg, direction,
		node.Value, UCB1(node), node.depth,
		node.action, len(node.UntriedActions),
		node.Visits, len(node.Children),
		stateID)
}

func (node *MCTSNode) ShowTrace() {
	cur := *node
	cur.ShowMsg("<-")

	for cur.Parent != nil {
		cur = *cur.Parent
		cur.ShowMsg("<-")
	}
}
